<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width:100px;height:100px;background: red;position: absolute;left:0;top:0;}
    </style>
</head>
<body>
    <div class="box">hello world</div>
</body>
<script>

    var oBox = document.querySelector(".box");
    var clientW = document.documentElement.clientWidth;
    var clientH = document.documentElement.clientHeight;
    var oBoxW = oBox.offsetWidth;
    var oBoxH = oBox.offsetHeight;

    // 先读，要处理从来没存过时的读取
    let pos = localStorage.getItem("pos");
    // 解析
    pos = pos ? JSON.parse(pos) : {x:0,y:0};
    // 设置
    oBox.style.left = pos.x + "px";
    oBox.style.top = pos.y + "px";

    oBox.onmousedown = function(eve){
        var downE = eve || window.event;
        downE.preventDefault();
        document.onmousemove = function(eve){
            var moveE = eve || window.event;
            var l = moveE.pageX - downE.offsetX;
            var t = moveE.pageY - downE.offsetY;
            if(l < 0) l = 0;
            if(t < 0) t = 0;
            if( l > clientW-oBoxW ) l = clientW-oBoxW;
            if( t > clientH-oBoxH ) t = clientH-oBoxH;
            oBox.style.left = l + "px"
            oBox.style.top = t + "px"
        }
        document.onmouseup = function(){
            document.onmousemove = null;
            document.onmouseup = null;

            // 找到坐标
            const obj = {
                x:oBox.offsetLeft,
                y:oBox.offsetTop
            }
            // 记住位置
            localStorage.setItem("pos", JSON.stringify(obj));
        }
    }

    
</script>
</html>